﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ApplicationErrorHandler.cs" company="TechBits">
//   Copyright (c) TechBits. All rights reserved.
// </copyright>
// <author>
//   Leandro G. Vacirca
// </author>
// <summary>
//   Defines the ApplicationErrorHandler type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace IntelliShortCut.Application
{
    using System;
    using System.Diagnostics;
    using System.Windows.Forms;
    using log4net;

    /// <summary>
    /// This class manages the unhandled exceptions of the application.
    /// </summary>
    public static class ApplicationErrorHandler
    {
        #region "Private Members"

        /// <summary>
        /// Logger interface.
        /// </summary>
        private static ILog _logger;

        #endregion

        #region "Public Methods"

        /// <summary>
        /// Initializes the application error handler.
        /// </summary>
        public static void Setup()
        {
            if (Debugger.IsAttached)
            {
                return;
            }

            Application.ThreadException += (sender, e) => Handle(e.Exception);
            AppDomain.CurrentDomain.UnhandledException += (sender, e) => Handle(e.ExceptionObject as Exception);
        }

       /// <summary>
        /// The handler of unhandled exceptions.
        /// </summary>
        /// <param name="exception">The exception.</param>
        public static void Handle(Exception exception)
        {
            var reference = Guid.NewGuid();

            _logger = LogManager.GetLogger(typeof(ApplicationErrorHandler));
            _logger.Fatal(reference, exception);

            MessageBox.Show(
                "There was an unexpected error. Please report the error to intellishortcut@techbits.com.ar.\n\nReference code: " + reference,
                "Error",
                MessageBoxButtons.OK,
                MessageBoxIcon.Error);

            Application.Exit();
        }

        #endregion
    }
}